package com.gwl.autoqq.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gwl.autoqq.constant.AutoQqApi;
import com.gwl.autoqq.pojo.RespDict;
import com.gwl.autoqq.pojo.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class Utils {

    @Value("${autoServer.ip}")
    public String ip;

    @Value("${autoServer.msgPort}")
    public int msgPort; // 发送信息

    @Value("${autoServer.serverPort}")
    public int serverPort; // 接收信息

    /**
     * 发送信息
     * @param respDict
     * @return
     */
    public AppHttpCodeEnum sendMsg(RespDict respDict) {
        Socket client = null;
        try {
            client = initClient();
            // 将字符中的特殊字符进行URL编码
            String payload = checkMsgType(respDict);

            if(payload==null) return AppHttpCodeEnum.ERROR_TYPE;
            log.info("发送体: " + payload);
            OutputStream output = client.getOutputStream();
            output.write(payload.getBytes(StandardCharsets.UTF_8));
            output.flush();
            output.close();
            return AppHttpCodeEnum.SUCCESS;
        } catch (UnknownHostException e) {
            return AppHttpCodeEnum.ERROR_HOST;
        } catch (IOException e) {
            return AppHttpCodeEnum.ERROR_IO;
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                return AppHttpCodeEnum.ERROR_CLOSE_FILE;
            }
        }
    }

    /**
     * 判断是群发还是私聊
     * @param respDict
     * @return
     */
    private String checkMsgType(RespDict respDict) {
        String msgType = respDict.getMsgType();  // 回复类型（群聊/私聊）
        String number = respDict.getNumber();  // 回复账号（群号/好友号）
        String msg = respDict.getMsg();  // 要回复的消息

        String encodedMsg = msg.replace(" ", "%20").replace("\n", "%0a");
        String lastMsg = " HTTP/1.1\r\nHost: 127.0.0.1:5700\r\nConnection: close\r\n\r\n";
        String startMsg = "GET ";

        switch (msgType){
            case "group":{
                return startMsg+AutoQqApi.SEND_GROUP_MSG +"?group_id=" + number + "&message=" + encodedMsg + lastMsg;
            }
            case "private":{
                return startMsg+AutoQqApi.SEND_PRAVATE_MSG+"?user_id=" + number + "&message=" + encodedMsg + lastMsg;
            }
            default:
                return null;
        }
    }

    /**
     * 监听接收信息 信息已经清洗好了, 还需要做过滤重复的条件，可以判断message_id进行过滤
     */
    public void receiveMessage(){
        ServerSocket listenSocket = null;
        try {
            listenSocket = new ServerSocket();
            SocketAddress socketAddress = new InetSocketAddress(ip, serverPort);
            listenSocket.bind(socketAddress);
            while (true){
                Socket clientSocket = listenSocket.accept();
//                System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

                InputStream inputStream = clientSocket.getInputStream();
                OutputStream outputStream = clientSocket.getOutputStream();

                byte[] buffer = new byte[1024];
                int length = inputStream.read(buffer);
                String request = new String(buffer, 0, length, "UTF-8");
                // 过滤请求
                Pattern pattern = Pattern.compile("\\{.*\\}");
                Matcher matcher = pattern.matcher(request);
                JSONObject response = null;
                if (matcher.find()) {
                    String json = matcher.group(0);
                    response = JSON.parseObject(json);
                }

                // 收到信息事件
                if(response.getString("post_type").equals("message")){
                    String message_type = response.getString("message_type");
                    String time = response.getString("time");
                    String message_id = response.getString("message_id");
                    String message = response.getString("message");
                    String sender_user_id = response.getJSONObject("sender").getString("user_id");
                    String sender_nickname = response.getJSONObject("sender").getString("nickname");
                    System.out.println("信息类型是: "+ message_type);
                    System.out.println( "收到的信息是: " + message);
                    System.out.println( "发送的用户id是: " + sender_user_id);
                    System.out.println( "发送给的用户id是: " + sender_nickname);
                    System.out.println( "时间是: " + svTime(time));
                    System.out.println( "消息id是: " + message_id);
                    System.out.println( "========================================");
                    System.out.println();
                    System.out.println();
                }
                clientSocket.close();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public  String svTime(String timestamp){
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

        // 将时间戳转换为 Date 对象
        Date date = new Date(Long.parseLong(timestamp));

        // 使用 SimpleDateFormat 格式化 Date 对象
        return sdf.format(date);
    }


    /**
     * 初始化Socket
     * @return
     * @throws IOException
     */
    public Socket initClient() throws IOException {
        return new Socket(ip, msgPort);
    }


}
